package cn.zhz.cloud.common.config.web;

import cn.zhz.cloud.common.model.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * @author ZHZ
 * @date 2021-02-28
 * @apiNote 统一返回值拦截
 */

@Slf4j
@RestControllerAdvice
public class GlobalReturnConfig implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object result, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (result instanceof R) {
//            log.info("统一返回格式，返回值：{}", JSONUtil.toJsonStr(result));
            return result;
        }
        String uri = serverHttpRequest.getURI().getPath();
        //排除swagger相关返回值
        if(uri.contains("error") || uri.contains("swagger") || uri.contains("/v3/api-docs") || uri.contains("/csrf")|| uri.contains("/actuator/prometheus")){
            return result;
        }

        //        log.info("统一返回格式，返回值：{}", JSONUtil.toJsonStr(resultUpdate));
        return R.ok(result);

    }
}
